#include "Helper.h"
#include <algorithm>


void InitRand()
{
	srand(unsigned int(time(NULL)));
}

double Randrand()
{
	// randomized random number generator

	return rand()/(double)RAND_MAX;
}

float SafeSum(const vector<float>& vcVec_)
{
	double dSum=.0;
	for(unsigned int i=0;i<vcVec_.size();i++)
		dSum += (double)vcVec_[i];				// using doubles is an easier way not to loose significant precision when adding floats ;)
	return (float)dSum;
}

float ExtraSafeSum(const vector<float>& vcVec_)
{
	if(vcVec_.empty()) return 0;

	vector<float> vVec = vcVec_;

	std::sort(vVec.begin(),vVec.end()); //make sure we always add numbers with closest magnitudes

	int nSize = vVec.size()/2;

	while(nSize!=1)
	{
		// to make sure that 
		vector<float> vTemp(nSize,0);
		if(vTemp.size()%2)
			vTemp.push_back(0); // If has uneven length, make it even length
		for(int i=0;i<nSize;i++)
		{
			vTemp[i]=vVec[i*2]+vVec[i*2+1];
		}
		vVec  = vTemp;
		nSize = vVec.size()/2;
	}
	return vVec[0]+vVec[1];
}

void AssignVec3(vector<float>* vector, const float& val0, const float& val1, const float& val2)
{
	(*vector).resize(3,0);
	(*vector)[0] = val0;
	(*vector)[1] = val1;
	(*vector)[2] = val2;
}

void AssignVec4(vector<float>* vector, const float& val0, const float& val1, const float& val2, const float& val3)
{
	(*vector).resize(4,0);
	(*vector)[0] = val0;
	(*vector)[1] = val1;
	(*vector)[2] = val2;
	(*vector)[3] = val3;
}

int RandIdx(int nTotal_)
{
	int nResult = int(Randrand()*nTotal_);
	return nResult==nTotal_ ? nResult-1:nResult; // function should return nTotal_-1 or lower
}

int RandLim(int nLower_, int nUpper_)
{
	return nLower_ + RandIdx(nUpper_-nLower_);
}

double RandLim( double dLower_, double dUpper_ )
{
    return dLower_ + (dUpper_-dLower_)*Randrand();
}